import request from "@/tool/Request/Request";
import {AxiosResponse} from "axios";
import Global from "@/store/Global";
// import SHA256 from "@/Function/security/encryption/SHA256";

export default class Login {
    static login(body: LoginData/*, callback: LoginRes*/): Promise<AxiosResponse<LoginResponse>> {
        const loginData:LoginData = {
            username: body.username,
            password: body.password,
        };
        return new Promise<AxiosResponse>(async (resolve: PromiseResolve, reject: PromiseReject) => {
            // await SHA256.Sha256(loginData.password).then(encryptionKey=>{
            //     debugger
            //     loginData.password = encryptionKey;
            // })
            await request.login(loginData).then((res: AxiosResponse<LoginResponse>) => {
                //设置自动登录
                Global.setAutoLogin(true)
                Login.saveToken(res);
                resolve({} as AxiosResponse<LoginResponse>);
                // callback && callback(res as LoginResponse);
            }).catch((err) => {
                console.error(err);
                reject(err);
            })
        })
    }

    static postRefreshToken() {
        request.postRefreshToken(Global.token).then((res: AxiosResponse<LoginResponse>) => {
            Login.saveToken(res);
        })
    }

    private static saveToken(res: AxiosResponse<LoginResponse>) {
        if (Global.isAutoLogin) {
            localStorage.setItem(Global.Token, <string>res.data.token);
            localStorage.setItem(Global.RefreshToken, <string>res.data.refreshToken);
        } else {
            sessionStorage.setItem(Global.Token, <string>res.data.token)
            sessionStorage.setItem(Global.RefreshToken, <string>res.data.refreshToken);
        }
    }
}

// type LoginRes = (res: LoginResponse) => void

